<template>
  <view class="mine-warp">
    <!-- #ifdef H5 -->
    <van-nav-bar title="个人中心"></van-nav-bar>
    <!-- #endif -->
    <scroll-view scroll-y="true" class="mine-content" :style="mineContentH5">
      <view class="userinfo">
        <view class="icon-top"></view>
        <view class="icon-head" @tap="massageEdit">
          <view class="img-head" :class="`img-head${data.info.picture}`">
            <view class="img-logo-default" v-if="logoType === 'default'"></view>
            <view class="img-logo-new" v-else></view>
          </view>
          <view class="editText" v-if="loginStatus">编辑个人信息</view>
        </view>
        <view class="name-number" v-if="loginStatus">
          <view class="account-info">
            <view class="user-name">
              {{ data.info.accountNumber }}
            </view>
            <!-- unit true非企业 false 企业 -->
            <!-- 企业用户，且包含多个用户 -->
            <view
              class="switch-account"
              v-if="!data.info.unit && data.info?.accountInfoList?.length > 0"
              @tap="changeAccount">
              <text class="iconfont icon-switch-account"></text>
              切换账户
            </view>
            <!-- 企业用户，且只有其他1个用户 -->
            <view
              class="switch-account"
              v-else-if="!data.info.unit && data.info?.accountInfoList?.length == 0"
              @tap="createAccount">
              <text class="iconfont icon-switch-account"></text>
              切换账户
            </view>
            <!-- 个人用户，且有多个企业 -->
            <view
              class="switch-account"
              v-else-if="data.info.unit && data.info?.accountInfoList?.length > 0"
              @tap="changeAccount">
              <text class="iconfont icon-switch-account"></text>
              切换账户
            </view>
          </view>
          <view class="current-points" @tap="jumpEquity">
            <view class="progress-bg">
              <text
                class="progress"
                :style="`width: ${
                  (data.info.startExperience / data.info.endExperience) * 100
                }%`"></text>
            </view>
          </view>
          <view class="user-level" @tap="jumpEquity">
            <text style="color: #fff">
              {{ data.info.levelName }}
            </text>
            <text class="points">
              {{ data.info.startExperience }}/{{ data.info.endExperience }}
            </text>
            <text class="iconfont icon-arrow-right"></text>
          </view>
          <view class="user-label" v-if="data.labelNameList && data.labelNameList?.length > 0">
            <template v-for="(item, index) in data.labelNameList" :key="index">
              <text class="tag" v-if="index < 3">{{ item }}</text>
            </template>
            <text v-if="data.labelNameList?.length > 3" style="margin-left: 10px">...</text>
          </view>
        </view>
        <view class="name-number-login" @tap="goLogin" v-else>点击登录</view>
        <view class="icon-bottom"></view>
      </view>
      <!-- <view class="space" style="height: 30px;width: 100vw;background-color: #f1f2f3;"></view> -->
      <view class="money-contain">
        <view class="bodyMoney">
          <view class="bodyPadding">
            <view class="corporateWallet" @tap="jumpToMoneywater" v-if="!data.info.unit">
              <view class="bodyText">企业钱包(元)</view>
              <view class="moneyNum">
                {{ data.fundData.unitBalance ? data.fundData.unitBalance : '--' }}
              </view>
            </view>
            <view class="borderRight" v-if="!data.info.unit"></view>
            <view class="corporateWallet" @tap="jumpToMoneywater">
              <view class="bodyText">个人钱包(元)</view>
              <view class="moneyNum">
                {{ data.fundData.personalBalance ? data.fundData.personalBalance : '--' }}
              </view>
            </view>
            <view class="borderRight"></view>
            <view class="corporateWallet" @tap="goToCoupon">
              <view class="bodyText">优惠券(张)</view>
              <view class="moneyNum">{{ data.couponNum || '--' }}</view>
            </view>
          </view>
        </view>
      </view>
      <!-- <view class="space" style="height: 30px;width: 100vw;background-color: #f1f2f3;"></view> -->
      <view class="contain">
        <view class="content">
          <view class="title">充电服务</view>
          <view class="item" @tap.stop="jumpToRecharge">
            <view class="img rechargeImage"></view>
            <view class="itemname">充值</view>
          </view>
          <view class="item" @tap.stop="jumpToDrawback">
            <view class="img drawbackImage"></view>
            <view class="itemname">退款</view>
          </view>
          <view class="item" @tap.stop="jumpToMyCar">
            <view class="img myCarImage"></view>
            <view class="itemname">我的爱车</view>
          </view>
          <view class="item" @tap.stop="jumpToTicket">
            <view class="img ticketImage"></view>
            <view class="itemname">开票</view>
          </view>
        </view>
      </view>
      <view class="contain">
        <view class="content">
          <view class="title">更多服务</view>
          <view class="item" @tap.stop="jumpToMessage">
            <view class="img messageImage"></view>
            <view class="zan-badge" v-if="data.total">{{ data.total }}</view>
            <view class="itemname">通知</view>
          </view>
          <view class="item" @tap.stop="jumpToPhone">
            <view class="img kefuImage"></view>
            <view class="itemname">客户服务</view>
          </view>
          <view class="item" @tap.stop="jumpToChargeSet">
            <view class="img chargeSetting"></view>
            <view class="itemname">充电设置</view>
          </view>
          <view class="item" @tap.stop="jumpToSet">
            <view class="img settingImage"></view>
            <view class="itemname">设置</view>
          </view>
        </view>
      </view>
    </scroll-view>
    <Tabber ref="tabber" :select="4"></Tabber>
    <PopupUser ref="popupUserRef"></PopupUser>
    <uni-popup ref="phoneRef" type="dialog" class="popup-phone">
      <view class="box-wrap">
        <view class="title-wrap">请选择客服电话</view>
        <view class="info-wrap">
          <view
            v-for="(item, index) in data.phoneList"
            :key="index"
            class="item-wrap"
            :class="{ 'item-top': index === 0 }"
            @tap="tapPhone(index)">
            <!-- <view class="iconfont icon-user"></view> -->
            <view class="text" :class="{ text1: data.selectInd === index }">
              {{ item.phone }}
            </view>
            <view
              class="iconfont icon-select"
              :class="{ 'select-show': data.selectInd === index }"></view>
          </view>
        </view>
        <view class="btn-wrap">
          <button class="btn btn1" @tap="hide">取消</button>
          <button class="btn btn2" @tap="tapPhoneCall">去拨打</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import {
  getToken,
  setToken,
  getUserId,
  setUserId,
  setMoreCharge,
  getSystemInfo,
  getwv,
  setToastInstance,
} from '@mixins/info';
import Tabber from '@/components/tabber/tabber.vue';
import PopupUser from '@/components/popupUser/popupUser.vue';
import { uniLogin } from '@/utils/api';
import { getAccount, queryLabelByUserId, switchAccount, countEntity } from '@/service/apis/mine';
import { callTel, saveItem } from '@/utils/util';
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

// 分享
onShareAppMessage(() => {
  return {
    title: '',
    path: '/pages/stationMap/stationMap',
  };
});

const $toast: any = inject('$Toast');

const appType = import.meta.env.VITE_VUE_APP_TYPE;
const logoType = import.meta.env.VITE_VUE_LOGO_TYPE;

console.log('appType', logoType);

const data = reactive({
  info: {} as any,
  fundData: {} as any,
  accountInfoList: [] as any,
  labelNameList: [] as any,
  walletId: '',
  couponNum: '',
  selectInd: 0,
  selectPhone: '4006820060',
  total: 0,
  phoneList: [
    {
      phone: 4006820060,
    },
    {
      phone: 16608305566,
    },
  ],
});

const mineContentH5 = computed(() => {
  // #ifdef H5
  return `height: calc(100vh - ${getwv(77)}px - ${getSystemInfo().navHeight}px)`;
  // #endif
  return '';
});

const loginStatus = computed(() => {
  return getToken();
});

const getLabelByUserId = () => {
  queryLabelByUserId({}, { account: { accountId: getUserId() } })
    .then((res: any) => {
      console.log(res);
      if (res) {
        data.info = res;
        data.accountInfoList = res.accountInfoList || [];
        data.accountInfoList = res.accountInfoList.map((item: any) => ({
          accountNumber: item.accountNumber,
          userId: item.id,
        }));
        data.labelNameList = res.labelNameList || [];
        data.total = res.total;
        setMoreCharge(res.moreCharging);
        saveItem('accountNumber', data.info.accountNumber);
      }
    })
    .catch(() => {});
  getAccountData();
  getCountEntity();
};
const getAccountData = () => {
  getAccount(
    { originalAccountId: getUserId(), accountType: 0 },
    { account: { accountId: getUserId() } }
  )
    .then((res: any) => {
      console.log(res);
      if (res) {
        data.fundData = res;
        data.walletId = res.id;
        saveItem('walletId', data.walletId);
      }
    })
    .catch(() => {});
};

const getCountEntity = () => {
  countEntity({})
    .then((res: any) => {
      data.couponNum = res;
    })
    .catch(() => {});
};

let page = ref('');

onLoad((option: any) => {
  page.value = option.page || '/pages/mine/mine';
});

onShow(() => {
  if (loginStatus.value) {
    getLabelByUserId();
  }
});
const popupUserRef = ref();
const changeAccount = () => {
  console.log(data.accountInfoList);
  popupUserRef.value?.show(data.accountInfoList, page.value);
};

const createAccount = () => {
  uni.showModal({
    content: `您当前无个人账号，是否需要为您立即创建？个人账号: ${data.info.mobile}`,
    confirmText: '立即创建',
    showCancel: true,
    success: async e => {
      if (e.confirm) {
        // 获取code
        const code = await uniLogin('weixin');
        // #ifdef MP-WEIXIN
        if (!code) return;
        // #endif
        switchAccount(
          {
            mobile: data.info.mobile,
            unit: data.info.unit,
            code: code,
          },
          { account: { accountId: getUserId() } }
        )
          .then((res: any) => {
            console.log(res);
            setToken(res.token);
            setUserId(res.userId);
            setMoreCharge(res.moreCharging);
            getLabelByUserId();
          })
          .catch(() => {});
      }
    },
  });
};

// 跳转到个人信息修改
const massageEdit = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/personalData/personalData`,
  });
};
// 跳转到权益页面
const jumpEquity = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/equity/equity`,
  });
};
// 跳转到钱包流水
const jumpToMoneywater = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/walletBill/walletBill?id=${data.walletId}&unit=${data.info.unit}`,
  });
};
// 跳转到优惠券
const goToCoupon = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/coupon/couponList`,
  });
};
// 跳转到充值页面
const jumpToRecharge = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/recharge/recharge?accountNumber=${data.info.accountNumber}`,
  });
};
// 跳转到退款
const jumpToDrawback = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/drawback/drawback?accountNumber=${data.info.accountNumber}`,
  });
};
// 跳转到车辆绑定
const jumpToMyCar = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/chargeCar/carList`,
  });
};
// 跳转到开票
const jumpToTicket = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/myBilling/myBilling`,
  });
};
// 跳转到站点收藏
const jumpToCollect = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/myCollect/myCollect`,
  });
};
// 跳转到通知
const jumpToMessage = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/myNotice/myNotice`,
  });
};
// 跳转到客服
const phoneRef = ref();

const goLogin = () => {
  uni.navigateTo({
    url: `/pages/login/login?page=/pages/mine/mine`,
  });
};
const jumpToPhone = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  // if (appType === 'pnd') {
  //   uni.makePhoneCall({
  //     phoneNumber: '4006079990',
  //     success: () => {},
  //     fail: () => {
  //       $toast({ title: '拨打电话失败' });
  //     },
  //   });
  // } else {
  uni.navigateTo({
    url: '/pagesMyCenter/customerService/customerService',
  });
  // uni.showModal({
  //   title: '温馨提示',
  //   content: '请联系客服：4006820060',
  //   success: res => {
  //     if (res.confirm) {
  //       uni.makePhoneCall({
  //         phoneNumber: '4006820060',
  //         success: () => {},
  //         fail: () => {
  //           $toast({ title: '拨打电话失败' });
  //         },
  //       });
  //     }
  //   },
  // });
  // }
};
const hide = () => {
  phoneRef.value?.close();
};

const tapPhone = (inx: number) => {
  data.selectInd = inx;
  if (inx == 0) {
    data.selectPhone = '4006820060';
  } else {
    data.selectPhone = '16608305566';
  }
};

const tapPhoneCall = () => {
  if (data.selectInd < 0) {
    return;
  }
  console.log(data.selectPhone);
  callTel(data.selectPhone);
};

// 跳转到设置
const jumpToSet = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/setting/setting?accountNumber=${data.info.accountNumber}`,
  });
};
const jumpToChargeSet = () => {
  if (!loginStatus.value) {
    goLogin();
    return;
  }
  uni.navigateTo({
    url: `/pagesMyCenter/setting/security`,
  });
};
// #ifdef H5
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${getSystemInfo().statusBarHeight}px`;
});
// #endif
</script>

<style lang="scss">
page {
  background-color: #f4f4f4;
}
</style>
<style lang="scss" scoped>
@import './index.scss';
</style>